package com.liangsui.mss.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liangsui.mss.constants.Constants;
import com.liangsui.mss.domain.*;
import com.liangsui.mss.dto.PurchaseDto;
import com.liangsui.mss.dto.PurchaseFormDto;
import com.liangsui.mss.dto.PurchaseItemDto;
import com.liangsui.mss.mapper.InventoryLogMapper;
import com.liangsui.mss.mapper.MedicinesMapper;
import com.liangsui.mss.mapper.PurchaseItemMapper;
import com.liangsui.mss.mapper.PurchaseMapper;
import com.liangsui.mss.service.PurchaseService;
import com.liangsui.mss.utils.IdGeneratorSnowflake;
import com.liangsui.mss.vo.DataGridView;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;

/**
* @author zhang
* @description 针对表【stock_purchase】的数据库操作Service实现
* @createDate 2022-12-06 14:18:42
*/
@DubboService(timeout = 5000)
@Transactional
public class PurchaseServiceImpl extends ServiceImpl<PurchaseMapper, Purchase>
    implements PurchaseService{

    @Autowired
    private PurchaseMapper purchaseMapper;

    @Autowired
    private PurchaseItemMapper purchaseItemMapper;

    @Autowired
    private InventoryLogMapper inventoryLogMapper;

    @Autowired
    private MedicinesMapper medicinesMapper;

    @Override
    public DataGridView listPurchasePage(PurchaseDto purchaseDto) {
        Page<Purchase> page = new Page<>(purchaseDto.getPageNum(), purchaseDto.getPageSize());
        QueryWrapper<Purchase> qw = new QueryWrapper<>();
        //供应商
        qw.eq(StringUtils.isNotBlank(purchaseDto.getProviderId()),
                Purchase.COL_PROVIDER_ID, purchaseDto.getProviderId());
        //申请人
        qw.like(StringUtils.isNotBlank(purchaseDto.getApplyUserName()),
                Purchase.COL_APPLY_USER_NAME, purchaseDto.getApplyUserName());
        //状态
        qw.eq(StringUtils.isNotBlank(purchaseDto.getStatus()),
                Purchase.COL_STATUS, purchaseDto.getStatus());
        qw.orderByDesc(Purchase.COL_CREATE_TIME);
        this.purchaseMapper.selectPage(page, qw);
        return new DataGridView(page.getTotal(), page.getRecords());
    }

    @Override
    public Purchase getPurchaseById(String purchaseId) {
        Purchase purchase = this.purchaseMapper.selectById(purchaseId);
        return purchase;
    }

    @Override
    public int doAudit(String purchaseId, SimpleUser simpleUser) {
        Purchase purchase = this.purchaseMapper.selectById(purchaseId);
        purchase.setStatus(Constants.STOCK_PURCHASE_STATUS_2);//设置状态为待审核
        purchase.setApplyUserName(simpleUser.getUserName());
        purchase.setApplyUserId(Long.valueOf(simpleUser.getUserId().toString()));
        return this.purchaseMapper.updateById(purchase);
    }

    @Override
    public int doInvalid(String purchaseId) {
        Purchase purchase = this.purchaseMapper.selectById(purchaseId);
        purchase.setStatus(Constants.STOCK_PURCHASE_STATUS_5);//设置状态为作废
        return this.purchaseMapper.updateById(purchase);
    }

    @Override
    public int auditPass(String purchaseId) {
        Purchase purchase = this.purchaseMapper.selectById(purchaseId);
        purchase.setStatus(Constants.STOCK_PURCHASE_STATUS_3);//设置状态为审核通过
        return this.purchaseMapper.updateById(purchase);
    }

    @Override
    public int auditNoPass(String purchaseId, String auditMsg) {
        Purchase purchase = this.purchaseMapper.selectById(purchaseId);
        purchase.setStatus(Constants.STOCK_PURCHASE_STATUS_4);//设置状态为审核不通过
        purchase.setAuditMsg(auditMsg);
        return this.purchaseMapper.updateById(purchase);
    }

    @Override
    public List<PurchaseItem> getPurchaseItemById(String purchaseId) {
        if (purchaseId != null) {
            QueryWrapper<PurchaseItem> qw = new QueryWrapper<>();
            qw.eq(PurchaseItem.COL_PURCHASE_ID, purchaseId);
            return this.purchaseItemMapper.selectList(qw);
        }
        return Collections.EMPTY_LIST;
    }

    @Override
    public int addPurchaseAndItem(PurchaseFormDto purchaseFormDto) {
        Purchase purchase = this.purchaseMapper.selectById(purchaseFormDto.getPurchaseDto().getPurchaseId());
        if (purchase != null) {
            //删除之前的数据
            this.purchaseMapper.deleteById(purchase.getPurchaseId());
            //删除之前的详情数据
            QueryWrapper<PurchaseItem> qw = new QueryWrapper<>();
            qw.eq(PurchaseItem.COL_PURCHASE_ID, purchase.getPurchaseId());
            this.purchaseItemMapper.delete(qw);
        }
        Purchase purchase1 = new Purchase();
        BeanUtils.copyProperties(purchaseFormDto.getPurchaseDto(), purchase1);
        purchase1.setStatus(Constants.STOCK_PURCHASE_STATUS_1);//未提交
        purchase1.setCreateBy(purchaseFormDto.getPurchaseDto().getSimpleUser().getUserName());
        purchase1.setCreateTime(DateUtil.date());
        int insert = this.purchaseMapper.insert(purchase1);
        //保存详情数据
        for (PurchaseItemDto item : purchaseFormDto.getPurchaseItemDtos()) {
            PurchaseItem purchaseItem = new PurchaseItem();
            BeanUtils.copyProperties(item, purchaseItem);
            purchaseItem.setPurchaseId(purchase1.getPurchaseId());
            purchaseItem.setItemId(IdGeneratorSnowflake.snowflakeId().toString());
            this.purchaseItemMapper.insert(purchaseItem);
        }
        return insert;
    }

    @Override
    public int addPurchaseAndItemToAudit(PurchaseFormDto purchaseFormDto) {
        Purchase purchase = this.purchaseMapper.selectById(purchaseFormDto.getPurchaseDto().getPurchaseId());
        if(null!=purchase){
            //删除之前的数据 stock_purchase
            this.purchaseMapper.deleteById(purchase.getPurchaseId());
            //删除之前的详情数据 stock_purchase_item
            QueryWrapper<PurchaseItem> qw=new QueryWrapper<>();
            qw.eq(PurchaseItem.COL_PURCHASE_ID, purchase.getPurchaseId());
            this.purchaseItemMapper.delete(qw);
        }
        //保存采购单主表数据
        Purchase newPurchase = new Purchase();
        BeanUtil.copyProperties(purchaseFormDto.getPurchaseDto(), newPurchase);
        newPurchase.setStatus(Constants.STOCK_PURCHASE_STATUS_2);//待审核
        newPurchase.setCreateBy(purchaseFormDto.getPurchaseDto().getSimpleUser().getUserName());
        newPurchase.setCreateTime(DateUtil.date());
        //设置申请人和申请人的ID
        newPurchase.setApplyUserId(Long.valueOf(purchaseFormDto.getPurchaseDto().getSimpleUser().getUserId().toString()));
        newPurchase.setApplyUserName(purchaseFormDto.getPurchaseDto().getSimpleUser().getUserName());
        int a = this.purchaseMapper.insert(newPurchase);
        //保存详情数据
        for (PurchaseItemDto item : purchaseFormDto.getPurchaseItemDtos()) {
            PurchaseItem purchaseItem=new PurchaseItem();
            BeanUtil.copyProperties(item, purchaseItem);
            purchaseItem.setPurchaseId(newPurchase.getPurchaseId());
            purchaseItem.setItemId(IdGeneratorSnowflake.snowflakeId().toString());
            this.purchaseItemMapper.insert(purchaseItem);
        }
        return a;
    }

    @Override
    @Transactional
    public int doInventory(String purchaseId, SimpleUser currentSimpleUser) {
        Purchase purchase = this.purchaseMapper.selectById(purchaseId);
        if (purchase != null || purchase.getStatus().equals(Constants.STOCK_PURCHASE_STATUS_3)){
            //查询详情
            QueryWrapper<PurchaseItem> qw = new QueryWrapper();
            qw.eq(PurchaseItem.COL_PURCHASE_ID, purchase.getPurchaseId());
            List<PurchaseItem> list = this.purchaseItemMapper.selectList(qw);
            //保存到stock_inventory_log表
            for (PurchaseItem purchaseItem : list) {
                InventoryLog inventoryLog=new InventoryLog();
                inventoryLog.setInventoryLogId(purchaseItem.getItemId());
                inventoryLog.setPurchaseId(purchaseItem.getPurchaseId());
                inventoryLog.setMedicinesId(purchaseItem.getMedicinesId());
                inventoryLog.setInventoryLogNum(purchaseItem.getPurchaseNumber());
                inventoryLog.setTradePrice(purchaseItem.getTradePrice());
                inventoryLog.setTradeTotalAmount(purchaseItem.getTradeTotalAmount());
                inventoryLog.setBatchNumber(purchaseItem.getBatchNumber());
                inventoryLog.setMedicinesName(purchaseItem.getMedicinesName());
                inventoryLog.setMedicinesType(purchaseItem.getMedicinesType());
                inventoryLog.setPrescriptionType(purchaseItem.getPrescriptionType());
                inventoryLog.setProducterId(purchaseItem.getProducterId());
                inventoryLog.setConversion(purchaseItem.getConversion());
                inventoryLog.setUnit(purchaseItem.getUnit());
                inventoryLog.setCreateTime(DateUtil.date());
                inventoryLog.setCreateBy(currentSimpleUser.getUserName());
                //保存数据
                inventoryLogMapper.insert(inventoryLog);
                //更新药品库存
                Medicines medicines = this.medicinesMapper.selectById(purchaseItem.getMedicinesId());
                medicines.setMedicinesStockNum(medicines.getMedicinesStockNum() + purchaseItem.getPurchaseNumber());
                medicines.setUpdateBy(currentSimpleUser.getUserName());
                medicines.setUpdateTime(DateUtil.date());
                this.medicinesMapper.updateById(medicines);
            }
            //入库成功
            purchase.setStatus(Constants.STOCK_PURCHASE_STATUS_6);
            purchase.setStorageOptUser(currentSimpleUser.getUserName());
            purchase.setStorageOptTime(DateUtil.date());
            return this.purchaseMapper.updateById(purchase);
        }
        return -1;
    }
}




